//班级学生响应数据
let classStudentData = new Array();
let studentData;
let allSelectData;
let tableData;

layui.use([ 'form', 'table', 'laytpl', 'step'], function () {
    let $ = layui.$,
        form = layui.form,
        step = layui.step,
        laytpl = layui.laytpl,
        table = layui.table;

    //判断是否有学生
    getAjax(true, "/api/student/hasStudent",null,function (res) {
        if(res.code === 0 && res.data === false){
            layer.open({

                title: false, //不显示标题栏
                closeBtn: false,
                area: '400px;',
                shade: 0.8,
                id: 'TOSTUDENTLIST', //设定一个id，防止重复弹出
                content: '您还未添加学生，请先添加学生信息！',
                yes: function(index){
                    window.location.href = '/page/student/student-list.html';
                    layer.close(index);
                }
            });
        }
        console.log(res);
    });

    let clipboard = new ClipboardJS('.copy-btn', {
        text: function(trigger) {
            return $(trigger).attr('data-name') + ": " +$(trigger).attr('data-comment');
        }
    });
    clipboard.on('success', function(e) {
        layerMsg("复制成功")
        e.clearSelection();
    });

    step.render({
        elem: '#stepForm',
        filter: 'stepForm',
        width: '100%', //设置容器宽度
        stepWidth: '750px',
        height: '500px',
        stepItems: [{
            title: '班级'
        }, {
            title: '印象'
        }, {
            title: '纪律'
        }, {
            title: '课堂'
        }, {
            title: '发言'
        }, {
            title: '作业'
        }, {
            title: '工作'
        }, {
            title: '成绩'
        }, {
            title: '期望'
        }, {
            title: '确认'
        }, {
            title: '完成'
        }]
    });


    //班级下拉选项
    let classInfo;
    getAjax(false, "/api/stu-class/search/list", '',function (res) {
        if(res.code == 0){
            if(res.data != null){
                classInfo = res.data;
                dataEngine(laytpl,'class-temp','class-view', res.data);
                form.render('select', 'class-form');
            }
        }else {
            let index = layer.alert(res.msg, {title: '提示', closeBtn: 0}, function () {
                layer.close(index);
                let iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            });
            return false;
        }
    });

    //下拉框选中
    form.on('select(stu-class)', function(e){
        let element = classInfo.filter(item => item.id == e.value)[0];
        if(!element){
            $(".class-top-body").remove();
        }else {
            //班级提示信息
            dataEngine(laytpl,'class-top-temp','class-top-view', element);
        }
    });


    //班级下一步
    form.on('submit(formStep)', function (data) {
        data.field['page'] = 1;
        data.field['limit'] = 100;
        getAjax(false, "/api/student/search/list", data.field,function (res) {
            if(res.code == 0){
                studentData = res.data;
                classStudentData = [];
                initSelect('impression', studentData);
            }else {
                layer.msg(res.msg)
            }
        });
        step.next('#stepForm');
        return false;
    });

    //印象下一步
    form.on('submit(formStep2)', function (data) {
        initSelect('discipline', studentData);
        step.next('#stepForm');
        return false;
    });

    //纪律下一步
    form.on('submit(formStep3)', function (data) {
        initSelect('classroom', studentData);
        step.next('#stepForm');
        return false;
    });

    //课堂下一步
    form.on('submit(formStep4)', function (data) {
        initSelect('speak', studentData);
        step.next('#stepForm');
        return false;
    });

    //发言下一步
    form.on('submit(formStep5)', function (data) {
        initSelect('homework', studentData);
        step.next('#stepForm');
        return false;
    });

    //作业下一步
    form.on('submit(formStep6)', function (data) {
        initSelect('job', studentData);//工作
        step.next('#stepForm');
        return false;
    });

    //工作下一步
    form.on('submit(formStep7)', function (data) {
        initSelect('score', studentData);
        step.next('#stepForm');
        return false;
    });

    //成绩下一步
    form.on('submit(formStep8)', function (data) {
        initSelect('expect', studentData);
        step.next('#stepForm');
        return false;
    });

    //期望下一步
    form.on('submit(formStep9)', function (data) {
        //获取所有选项
        allSelectData = new Array();
        allSelectData.push(buildSelectTableData('impression'));
        allSelectData.push(buildSelectTableData('discipline'));
        allSelectData.push(buildSelectTableData('classroom'));
        allSelectData.push(buildSelectTableData('speak'));
        allSelectData.push(buildSelectTableData('homework'));
        allSelectData.push(buildSelectTableData('job'));
        allSelectData.push(buildSelectTableData('score'));
        allSelectData.push(buildSelectTableData('expect'));

        //渲染数据模板
        dataEngine(laytpl, 'name-list-temp', 'name-list-view', allSelectData)

        //转化静态表格
        table.init('parse-table-demo', {
            height: 350,
            limit:1000
        });
        step.next('#stepForm');
        return false;
    });

    form.on('submit(formStep10)', function (data) {
        postAjax('/api/comment/auto', allSelectData, function (res) {
            //渲染表格
            tableData = buildCommentData(res);
            dataEngine(laytpl, 'comment-list-temp', 'comment-list-view',  tableData)
            //转化静态表格
            table.init('parse-table-comment', {
                height: 350,
                limit:1000
            });
        })
        step.next('#stepForm');
        return false;
    });

    $('.pre').click(function () {
        step.pre('#stepForm');
    });

    $('.next').click(function () {
        step.next('#stepForm');
    });

    $('#again').click(function () {
        postAjax('/api/comment/auto', allSelectData, function (res) {
            //渲染表格
            tableData = buildCommentData(res);
            dataEngine(laytpl, 'comment-list-temp', 'comment-list-view',  tableData)
            //转化静态表格
            table.init('parse-table-comment', {
                height: 350,
                limit:1000
            });
        })
    });

    $('#returnBtn').click(function () {
        layer.confirm('返回后当前评语会丢失，是否确定返回首页？', {btn : [ '确定', '取消' ]}, function(index) {
            parent.location.href = '/index.html';
            layer.close(index);
        });
    })

    $('#excelExport').click(function () {
        if(tableData && tableData.length > 0){
            postAjax("/api/comment/exportInit",tableData, function (result) {
                if(result.code === 0 && result.data){
                    window.open("/api/comment/export/excel/" + result.data);
                }
            })
        }
    })

    $('#wordExport').click(function () {
        if(tableData && tableData.length > 0){
            postAjax("/api/comment/exportInit",tableData, function (result) {
                if(result.code === 0 && result.data){
                    window.open("/api/comment/export/word/" + result.data);
                }
            })
        }
    })
});

function layerMsg(msg){
    layer.msg(msg);
}

function renderCheckbox(elemType) {
    let selObjArr = classStudentData.filter(v => v.type === elemType);
    for (const selObj of selObjArr) {
        let select = renderSelect(selObj, elemType);
        selObj['xmSelect'] = select;
    }
}

function renderSelect(selObj , elemType){
    let xmSelectObj = xmSelect.render({
        el: selObj.id,
        template({ item, sels, name, value }){
            if(item.evaluate && item.evaluate != ''){
                return item.name + '（' + getEvaluateName(elemType, item.evaluate) + '）' + '<span style="position: absolute; right: 10px; color: #8799a3">学号：'+item.stuCode+'</span>'
            }
            return item.name  + '<span style="position: absolute; right: 10px; color: #8799a3">学号：'+item.stuCode+'</span>'
        },
        model: {
            label: {
                type: 'block',
                block: {
                    //最大显示数量, 0:不限制
                    showCount: 0,
                    //是否显示删除图标
                    showIcon: false,
                }
            }
        },
        toolbar: {
            show: true,
        },
        filterable: true,
        data: selObj.data,
        hide(){
            reRenderOther(selObj.id ,elemType)
        }
    })
    return xmSelectObj
}



function reRenderOther(currentId, elemType) {
    let currentObj = classStudentData.filter(v => v.type === elemType && v.id === currentId)[0];
    let selObjArr = classStudentData.filter(v => v.type === elemType);
    let selectedValueArr = currentObj.xmSelect.getValue();
    for (const selectedValueArrElement of selectedValueArr) {
        selectedValueArrElement['evaluate'] = currentId
    }
    for (const selObj of selObjArr) {
        let oldSelectArr = selObj.data.filter(v => v.evaluate === currentId);
        let oldValue = oldSelectArr.map(v => v.value);
        let selectValue = selectedValueArr.map(v => v.value);
        for (const oldValueElement of oldValue) {
            if(!selectValue.includes(oldValueElement)){
                let filterElement = oldSelectArr.filter(v => v.value === oldValueElement)[0];
                delete filterElement.evaluate;
                delete filterElement.selected;
                delete filterElement.disabled;
            }
        }

        for (const selectedValue of selectedValueArr) {
            let sValue = selObj.data.filter(v => v.value === selectedValue.value)[0];
            sValue['evaluate'] = selectedValue.evaluate
            if(selectedValue['evaluate'] != selObj.id){
                sValue['disabled'] = true
            }else {
                sValue['selected'] = true
            }
        }
        selObj.xmSelect.update({
            data: selObj.data
        })
    }

}


function getEvaluateName(type, evaluate) {
    if(type.includes('expect')){
        if(evaluate.includes('good')){
            return '好学生'
        }
        if(evaluate.includes('unqualified')){
            return '差生'
        }
        if(evaluate.includes('qualified')){
            return '中等生'
        }
    }else {
        if(evaluate.includes('excellent')){
            return '优秀'
        }
        if(evaluate.includes('good')){
            return '良好'
        }
        if(evaluate.includes('unqualified')){
            return '不合格'
        }
        if(evaluate.includes('qualified')){
            return '合格'
        }
    }
    return '';
}

function initSelect(type, data) {
    let element = classStudentData.filter(v => v.type === type)[0];
    if(element){
       return;
    }
    let excellent = new Object();
    let good = new Object();
    let qualified = new Object();
    let unqualified = new Object();

    excellent['type'] = type;
    good['type'] = type;
    qualified['type'] = type;
    unqualified['type'] = type;

    excellent['id'] = '#' + type + '-excellent-select';
    good['id'] = '#' + type + '-good-select';
    qualified['id'] = '#' + type + '-qualified-select';
    unqualified['id'] = '#' + type + '-unqualified-select';

    excellent['data'] = new Array();
    good['data'] = new Array();
    qualified['data'] = new Array();
    unqualified['data'] = new Array();

    data.map( item => {
        excellent['data'].push(Object.assign({},{name: item.name ,stuCode: item.stuCode, value: item.id}))
        good['data'].push(Object.assign({},{name: item.name ,stuCode: item.stuCode, value: item.id}))
        qualified['data'].push(Object.assign({},{name: item.name ,stuCode: item.stuCode, value: item.id}))
        unqualified['data'].push(Object.assign({},{name: item.name ,stuCode: item.stuCode, value: item.id}))
    })

    classStudentData.push(excellent);
    classStudentData.push(good);
    classStudentData.push(qualified);
    classStudentData.push(unqualified);

    //渲染下拉框
    renderCheckbox(type);
}

function buildCommentData(res) {
    let tableData = new Array();
    let i = 0;
    for (const response of res.data) {
        let stuComment = new Object();
        stuComment.serial = ++i;
        stuComment.stuName = response.stuName;
        stuComment.comment = response.commentResultList.map(v => v.content).join('');
        tableData.push(stuComment);
    }
    return tableData;
}

function buildSelectTableData(type) {
    let typeObj = new Object();
    let typeList = classStudentData.filter(v => v.type === type);
    typeObj['type'] = getTypeName(type);
    typeObj['data'] = new Array();
    for (const any of typeList) {
        let listObj = new Object();
        if(any.id.includes('excellent')){
            listObj['name'] = "优秀";
        }else if(any.id.includes('good')){
            listObj['name'] = "良好";
        }else if(any.id.includes('unqualified')){
            listObj['name'] = "不合格";
        }else if(any.id.includes('qualified')){
            listObj['name'] = "合格";
        }
        let selected = any.xmSelect.getValue();
        listObj['value'] = ''
        if(selected && selected.length > 0){
            listObj['value'] = selected.map(v => v.name).join('，');
        }
        typeObj['data'].push(listObj);
    }
    return typeObj;
}

function getTypeName(type) {
    if(type.includes('impression')){
        return '印象';
    }
    if(type.includes('discipline')){
        return '纪律';
    }
    if(type.includes('classroom')){
        return '课堂';
    }
    if(type.includes('speak')){
        return '发言';
    }
    if(type.includes('homework')){
        return '作业';
    }
    if(type.includes('job')){
        return '工作';
    }
    if(type.includes('score')){
        return '成绩';
    }
    if(type.includes('expect')){
        return '期望';
    }
    return '';
}
